package com.hy.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hy.usercenter.common.ResultEnum;
import com.hy.usercenter.enums.TeamStatusEnum;
import com.hy.usercenter.exception.CommonException;
import com.hy.usercenter.model.domain.SysUser;
import com.hy.usercenter.model.domain.Team;
import com.hy.usercenter.model.domain.UserTeamRelation;
import com.hy.usercenter.model.dto.TeamQuery;
import com.hy.usercenter.model.dto.TeamUpdateRequest;
import com.hy.usercenter.model.vo.TeamUserVo;
import com.hy.usercenter.model.vo.UserVo;
import com.hy.usercenter.service.SysUserService;
import com.hy.usercenter.service.TeamService;
import com.hy.usercenter.mapper.TeamMapper;
import com.hy.usercenter.service.UserTeamRelationService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
* @author a
* @description 针对表【team(队伍表)】的数据库操作Service实现
* @createDate 2023-02-26 15:09:16
*/
@Service
public class TeamServiceImpl extends ServiceImpl<TeamMapper, Team>
    implements TeamService{

    @Autowired
    UserTeamRelationService userTeamRelationService;

    @Autowired
    SysUserService userService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addTeam(Team team, SysUser currentUser) {
        //1. 请求参数是否为空？
        if (Objects.isNull(team)) {
            throw new CommonException(ResultEnum.PARAMS_ERROR);
        }
        //2. 是否登录，未登录不让创建
        if (Objects.isNull(currentUser)) {
            throw new CommonException(ResultEnum.NO_LOGIN);
        }
        final Long id = currentUser.getId();
        //3. 校验信息
        //   1. 队伍人数 > 1且 小于 20
        Integer maxNum = Optional.ofNullable(team.getMaxNum()).orElse(0);
        if (maxNum < 1 || maxNum > 20) {
            throw new CommonException(ResultEnum.PARAMS_ERROR, "人数不再合理范围内");
        }
        //   2. 队伍标题 <= 20
        String name = team.getName();
        if (StringUtils.isBlank(name) || name.length() > 20) {
            throw new CommonException(ResultEnum.PARAMS_ERROR, "标题过长");
        }
        //   3. 描述 <= 512
        String description = team.getDescription();
        if (StringUtils.isNotBlank(description) && description.length() > 512) {
            throw new CommonException(ResultEnum.PARAMS_ERROR, "描述过长");
        }
        //   4. 是否公开（int）不传默认为0公开
        Integer status = Optional.ofNullable(team.getStatus()).orElse(0);
        TeamStatusEnum statusEnumByValue = TeamStatusEnum.getStatusEnumByValue(status);
        if (statusEnumByValue == null) {
            throw new CommonException(ResultEnum.PARAMS_ERROR, "不存在这种状态");
        }
        //   5. 如果status是加密状态一定要有密码，密码 <= 32
        if (TeamStatusEnum.SECRET.equals(statusEnumByValue)
                && StringUtils.isBlank(team.getPassword())
                || team.getPassword().length() > 32) {
            throw new CommonException(ResultEnum.PARAMS_ERROR, "密码设置不正确");
        }
        //   6. 超时时间 > 当前时间
        if (new Date().after(team.getExpireTime())) {
            throw new CommonException(ResultEnum.PARAMS_ERROR, "时间设置不正确");
        }
        // 4. 最多创建5个队伍 有bug，如果用户疯狂的点击可能创建100个队伍...
        QueryWrapper<Team> lqw = Wrappers.query();
        lqw.eq("user_id", id);
        long count = this.count(lqw);
        if (count > 5) {
            throw new CommonException(ResultEnum.PARAMS_ERROR, "创建队伍超过上限");
        }
        //4. 插入队伍用户到队伍表
        team.setId(null);
        team.setUserId(id);
        boolean save = this.save(team);
        if (!save || team.getId() == null) {
            throw new CommonException(ResultEnum.PARAMS_ERROR, "创建队伍失败");
        }
        //5. 插入用户 => 队伍关系到关系表
        UserTeamRelation userTeamRelation = new UserTeamRelation();
        userTeamRelation.setId(null);
        userTeamRelation.setUserId(id);
        userTeamRelation.setTeamId(team.getId());
        userTeamRelation.setJoinTime(new Date());

        save = userTeamRelationService.save(userTeamRelation);
        if (!save) {
            throw new CommonException(ResultEnum.PARAMS_ERROR, "创建队伍失败");
        }

        return 0L;
    }

    @Override
    public List<TeamUserVo> listTeamQuery(TeamQuery teamQuery, Boolean isAdmin) {

        Team team = new Team();
        BeanUtils.copyProperties(teamQuery, team);
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
        // 组合查询条件
        String description = teamQuery.getDescription();
        if (StringUtils.isNotBlank(description)) {
            queryWrapper.eq("description", description);
        }

        Long teamId = teamQuery.getId();
        if (teamId != null && teamId > 0) {
            queryWrapper.eq("id", teamId);
        }

        String name = teamQuery.getName();
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.eq("name", name);
        }

        Integer maxNum = teamQuery.getMaxNum();
        if (maxNum != null && maxNum > 0 ) {
            queryWrapper.eq("max_num", maxNum);
        }

        Integer status = teamQuery.getStatus();

        TeamStatusEnum statusEnumByValue = TeamStatusEnum.getStatusEnumByValue(teamQuery.getStatus());
        if (statusEnumByValue == null) {
            statusEnumByValue = TeamStatusEnum.PUBLIC;
        }
        if (!isAdmin && !statusEnumByValue.equals(TeamStatusEnum.PUBLIC)) {
            throw new CommonException(ResultEnum.NO_AUTHORITY);
        }
        queryWrapper.eq("status", statusEnumByValue.getValue());

        Long userId = teamQuery.getUserId();
        if (userId != null && userId > 0) {
            queryWrapper.eq("user_id", userId);
        }
        /**
         * 过滤时间为null或者当前时间之前的
         */
        queryWrapper.and(tj ->
                tj.isNull("expire_time")
                        .or()
                        .gt("expire_time", new Date()) );

        List<Team> teamList = this.list(queryWrapper);




        // 查询关联用户信息
        // 1.查询队伍信息和创建人信息
        // select * from team t left join sys_user u on t.user_id = u.id
        // 2.查询队伍和加入队伍的人员信息
        //   select * from team t left join
        //      user_team_relation ut on t.team_id = ut.team_id
        //      left join sys_user u on ut.user_id = u.user_id
        List<TeamUserVo> teamUserVos = new ArrayList<>();
        for (int i = 0; i < teamList.size(); i++) {
            TeamUserVo teamUserVo = new TeamUserVo();
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(team, teamUserVo);

            teamUserVos.add(teamUserVo);
            Long uid = teamList.get(i).getUserId();
            if (uid == null) {
                continue;
            }
            SysUser user = userService.getById(uid);
            if (user != null) {
                BeanUtils.copyProperties(user, userVo);
                teamUserVo.setUserVo(userVo);
            }
        }

        return teamUserVos;
    }

    @Override
    public boolean teamUpdate(TeamQuery teamQuery) {
        return false;
    }

    @Override
    public Boolean editTeamInfo(TeamUpdateRequest teamUpdateRequest, SysUser loginUser) {
        // 只有当前用户和管理员才能修改

        // 修改队伍为加密时，密码不能为空

        //空串不能被更新
        return false;
    }
}




